// index.ts
import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse ,InternalAxiosRequestConfig,AxiosError} from 'axios'
import ConfigUrl from '../assets/config/ts/config'
import router from "@/router";

type Result<T> = {
  data:T;
};
type Error={
  response:any
}
// 导出Request，可以用来自定义传递配置来创建实例
export class Request {
  // axios 实例
  instance: AxiosInstance
  // 基础配置，url和超时时间
  baseConfig: AxiosRequestConfig = {baseURL: '/api', timeout: 60000,headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      'x-app-id': '10040',
      'x-version': '',
      'x-platform':'web',
      'x-channel':'web',
      'x-public-ip': '',
      'x-mobile-brand': '',
      'x-mobile-model': '',
      'x-token': ''
    }}

  // index.ts
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(Object.assign(this.baseConfig, config))

    this.instance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        // 一般会请求拦截里面加token，用于后端的验证
        const token = localStorage.getItem('duokai_token') as string
        console.log(token,config.url);
        if(token) {
          config.headers = {
            'Content-Type': config.url == '/order' || config.url == '/stop' ? "multipart/form-data" : 'application/json;charset=UTF-8' ,
            'x-app-id': '10040',
            'x-version': '',
            'x-platform':'web',
            'x-channel':'web',
            'x-public-ip': '',
            'x-mobile-brand': '',
            'x-mobile-model': '',
            'x-token': config.url == '/launch' ? '' : token
          }
        }

        return config
      },
      (err: any) => {
        // 请求错误，这里可以用全局提示框进行提示
        return Promise.reject(err)
      },
    )

    this.instance.interceptors.response.use(
      (res: AxiosResponse) => {
        // 直接返回res，当然你也可以只返回res.data
        // 系统如果有自定义code也可以在这里处理
        return res
      },
      (err:Error | AxiosError) => {
        // 这里用来处理http常见错误，进行全局提示
        let message = "";
        switch (err.response.status) {
          case 400:
            message = "请求错误(400)";
            break;
          case 401:

            message = "未授权，请重新登录(401)";
              this.TokenError()



            // 这里可以做清空storage并跳转到登录页的操作
            break;
          case 403:
            message = "拒绝访问(403)";
            break;
          case 404:
            message = "请求出错(404)";
            break;
          case 408:
            message = "请求超时(408)";
            break;
          case 500:
            message = "服务器错误(500)";
            break;
          case 501:
            message = "服务未实现(501)";
            break;
          case 502:
            message = "网络错误(502)";
            break;
          case 503:
            message = "服务不可用(503)";
            break;
          case 504:
            message = "网络超时(504)";
            break;
          case 505:
            message = "HTTP版本不受支持(505)";
            break;
          default:
            message = `连接出错(${err.response.status})!`;
        }
        return Promise.reject(err.response)
      },
    )
  }

  // 定义请求方法
  public request(config: AxiosRequestConfig): Promise<AxiosResponse> {
    return this.instance.request(config)
  }
  public async get<T = any>(
    url: string,
    config?: AxiosRequestConfig
  ): Promise<AxiosResponse<Result<T>>> {
    let dataValue = await this.instance.get(url, config);
    return new Promise((resolve, reject) => {
      if (dataValue.data.code == 0) {
        resolve(dataValue.data)
      }
      else {
        reject(dataValue.data)
      }
    })
  }

  public async post<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<AxiosResponse<Result<T>>> {

    let dataValue = await this.instance.post(url, data, config);
    return new Promise((resolve, reject) => {
      if (dataValue.data.code == 0) {
        resolve(dataValue.data)
      }
      else{
        reject(dataValue.data)
      }
    })


    // return this.instance.post(url, data, config);
  }
  public async put<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<AxiosResponse<Result<T>>> {

    let dataValue = await this.instance.put(url, data, config);
    return new Promise((resolve, reject) => {
      if (dataValue.data.code == 0) {
        resolve(dataValue.data)
      }
      else{
        reject(dataValue.data)

      }
    })


    // return this.instance.post(url, data, config);
  }

  public TokenError = () => {
  };

}

// 默认导出Request实例
export default new Request({})